/*
 * Copyright (c) 2018. czmc All Rights Reserved.
 * Author: czmc
 * Email: zxc6355533@163.com
 * Encoding: UTF-8
 */

package top.stime21.myneighbours.api;

import com.google.gson.Gson;
import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import orgs.apache.commonss.codec.digests.DigestUtilss;
import top.stime21.myneighbours.utils.RSA;

/**
 * Created by czmc on 2017/2/7.
 */

public class ParamInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Map<String, Object> map = new HashMap<String, Object>();//请求集合
        Map<String, Object> head = new HashMap<String, Object>();//请求头
        Map<String, Object> data = new HashMap<String, Object>();

        String timestamp = System.currentTimeMillis() + "";
        Request oldRequest = chain.request();
        Set<String> set = oldRequest.url().queryParameterNames();
        for (String paramName : set) {
            //如果已经由Gson转换请求后则无需再次加密封装，直接传递就请求
            if(paramName.equals("data")) {
                return chain.proceed(oldRequest);
            }
            data.put(paramName, oldRequest.url().queryParameter(paramName));
        }
        String json = new Gson().toJson(data);
        String dataStr = Base64Utils.encodeBase64String(json);//对请求体进行base64编码
        String sign = "";
        StringBuilder sb = new StringBuilder();
        sb.append(timestamp);
        sb.append(dataStr);
        sign = DigestUtilss.md5Hex(sb.toString());
        head.put("sign", sign);
        head.put("timestamp", timestamp + "");//时间戳
        map.put("head", head);
        map.put("data", dataStr);
        String data1 = null;
        try {
            data1 = Base64Utils.encode(RSA.encryptByPublicKey(new Gson().toJson(map).getBytes(), ApiManager.Companion.getSECRET()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 添加新的参数
        HttpUrl.Builder authorizedUrlBuilder =oldRequest.url().newBuilder()
                .scheme(oldRequest.url().scheme())
                .host(oldRequest.url().host())
                .port(oldRequest.url().port())
                .addQueryParameter("data", data1);
        Logger.i(oldRequest.url().toString());
        Logger.json(json.toString());
        //移除旧参数
        for (String paramName : set) {
            authorizedUrlBuilder.removeAllQueryParameters(paramName);
        }
        //新的请求
        Request newRequest = oldRequest.newBuilder()
                .method(oldRequest.method(), oldRequest.body())
                .url(authorizedUrlBuilder.build())
                .build();
//            Logger.i(newRequest.method()+"--"+newRequest.url().query());
        return chain.proceed(newRequest);
    }
}
